var err_msg	= '<div class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>出错了 : &nbsp;</strong>{err}</div>';
var err_reg	= new RegExp('({err})', 'g');
var ws		= new WebSocket('ws://' + location.host + '/ws');
var ws_all	= new WebSocket('ws://' + location.host + '/tail_all');
var ws_tail = null;
var current_watcher_name = null;

$('#mdl-add').on('show.bs.modal', function(e) {	
	$(this).find('#err').empty();
});

$('#mdl-edit').on('show.bs.modal', function(e) {
	var btn		= $(e.relatedTarget);
	var name	= btn.data('watcher-name');
	var cmd		= btn.data('watcher-cmd');
	var dir		= btn.data('watcher-dir');
	var retries	= btn.data('watcher-retries');

	$(this).find('#org-name').val(name);
	$(this).find('#in-name').val(name);
	$(this).find('#in-cmd').val(cmd);
	$(this).find('#in-dir').val(dir);
	$(this).find('#in-retry').val(retries);
});

$('#mdl-tail').on('show.bs.modal', function(e) {
	var btn		= $(e.relatedTarget);
	var name	= btn.data('watcher-name');

	if (ws_tail != null) {
		ws_tail.close();
		ws_tail = null;
	}

	current_watcher_name = name;
	ws_tail = new WebSocket('ws://' + location.host + '/tail/' + name);
	ws_tail.onmessage = function(evt) {
		try {
			var data = JSON.parse(evt.data);
			var dom = $('#mdl-tail pre').get(0);

			if (dom != null) {
				if (data.action == 'tail_sync') {
					dom.innerHTML = data.data;
				} else {
					dom.innerHTML += data.data;
					var len = dom.innerHTML.length;
					if (len > 65536) {
						dom.innerHTML = dom.innerHTML.substring(len - 65536);
					}
				}
			}

			if (document.getElementById('enable_follow').checked)
				$('#mdl-tail pre').scrollTop(99999999);
		} catch (err) {
		}
	}
});

$('#mdl-tail').on('hide.bs.modal', function() {
	if (ws_tail != null) {
		ws_tail.close();
		ws_tail = null;
	}
});

function status2label(status) {
	if (status == 0) {
		return '<span class="badge badge-secondary">已停止</span>';
	} else if (status == 1) {
		return '<span class="badge badge-success">运行中</span>';
	} else if (status == 2) {
		return '<span class="badge badge-danger">已退出</span>';
	} else {
		return '<span class="badge badge-warning">重起中</span>';
	}
}

function watcher2html(watcher) {
	return '<td>' + watcher.name + '</td>'
		+ '<td class="status">' + status2label(watcher.status) + '</td>'
		+ '<td class="pid">' + (watcher.pid || '--') + '</td>'
		+ '<td class="cpu">0</td>'
		+ '<td class="vsz">0</td>'
		+ '<td class="res">0</td>'
		+ '<td class="start_time">' + (watcher.start_time || '--') + '</td>'
		+ '<td>'
		+ '<button onclick="start_watcher(\'' + watcher.name + '\')" class="btn btn-default btn-sm start" ' + (watcher.status == 1 ? 'disabled' : '') + '><i class="fa fa-play" aria-hidden="true"></i> 启动</button>&nbsp;'
		+ '<button onclick="stop_watcher(\'' + watcher.name + '\')" class="btn btn-default btn-sm stop" ' + (watcher.status != 1 ? 'disabled' : '') + '><i class="fa fa-stop" aria-hidden="true"></i> 停止</button>&nbsp;'
		+ '<button class="btn btn-default btn-sm" data-toggle="modal" data-target="#mdl-tail" data-watcher-name="'+ watcher.name + '"><i class="fa fa-list-alt" aria-hidden="true"></i> 日志</button>'
		+ '</td><td>'
		+ '<button class="btn btn-info btn-sm" data-toggle="modal" data-target="#mdl-edit" data-watcher-name="'+ watcher.name + '" data-watcher-cmd="' + watcher.cmd + '" data-watcher-dir="' + watcher.dir + '" data-watcher-retries="' + watcher.retry + '"><i class="fa fa-edit" aria-hidden="true"></i> 编辑</button>&nbsp;'
	//	+ '<button onclick="delete_watcher(\'' + watcher.name + '\')" class="btn btn-danger btn-sm delete" ' + (watcher.status == 1 ? 'disabled' : '') + '><i class="fa fa-trash" aria-hidden="true"></i> 删除</button>'
		+ '</td>';
}

function reload() {
	$.get('/api/reload', function(ret) {
		alert('重载成功');
	}, 'json');
}

// 重置指定程序日志
function reset_log() {
	$.post('/api/reset_log', {
		name : current_watcher_name
	}, function(ret) {
	}, 'json');
}

function add_watcher() {
	$.post('/api/add', {
		name: $('#form-add #in-name').val(),
		cmd: $('#form-add #in-cmd').val(),
		dir: $('#form-add #in-dir').val(),
		retry: $('#form-add #in-retry').val()
	}, function(ret) {
		if (ret.err != null) {
			var dom = $('#mdl-add #err').get(0);
			dom.innerHTML = err_msg.replace(err_reg, ret.err);
		} else {
			$('#mdl-add').modal('hide');
		}
	}, 'json');
}

function edit_watcher() {	
	$.post('/api/edit', {
		"org-name": $('#form-edit #org-name').val(),
		name: $('#form-edit #in-name').val(),
		cmd: $('#form-edit #in-cmd').val(),
		dir: $('#form-edit #in-dir').val(),
		retry: $('#form-edit #in-retry').val()
	}, function(ret) {
		if (ret.err != null) {
			var dom = $('#mdl-edit #err').get(0);
			dom.innerHTML = err_msg.replace(err_reg, ret.err);
		} else {
			$('#mdl-edit').modal('hide');
		}
	}, 'json');
}

function start_watcher(name) {
	$.get('/api/start?name=' + name, function(ret) {}, 'json');
}

function stop_watcher(name) {
	$.get('/api/stop?name=' + name, function(ret) {}, 'json');
}

function delete_watcher(name) {
	$.get('/api/delete?name=' + name, function(ret) {}, 'json');
}

ws.onclose = function(evt) {
	$('#conn-err').get(0).innerHTML = err_msg.replace(err_reg, '与Supervisor断开连接，请检查服务是否已关闭!!!');
}

ws.onmessage = function(evt) {
	try {
		var data = JSON.parse(evt.data);
		if (data.action == 'add') {
			var obj		= document.getElementById('watcher-' + (data.rename == null ? data.watcher.name : data.rename));
			var html	= watcher2html(data.watcher);

			if (obj == null) {
				var all = $('#table-watchers');
				var add = $('<tr id="watcher-' + data.watcher.name + '">' + html + '</tr>');
				all.append(add);
			} else {
				if (name != data.watcher.name) $(obj).prop('id', 'watcher-' + data.watcher.name);
				$(obj).html(html);
			}
		} else if (data.action == 'delete') {
			var dom = document.getElementById('watcher-' + data.watcher);
			if (dom != null) dom.remove();
		} else if (data.action == 'status_change') {
			$('#watcher-' + data.watcher + ' .status').html(status2label(data.status));
			$('#watcher-' + data.watcher + ' .start').attr('disabled', data.status == 1);
			$('#watcher-' + data.watcher + ' .stop').attr('disabled', data.status != 1);
			$('#watcher-' + data.watcher + ' .delete').attr('disabled', data.status == 1);
			$('#watcher-' + data.watcher + ' .pid').html(data.pid);
			$('#watcher-' + data.watcher + ' .cpu').html('0');
			$('#watcher-' + data.watcher + ' .vsz').html('0');
			$('#watcher-' + data.watcher + ' .res').html('0');
			$('#watcher-' + data.watcher + ' .start_time').html(data.start_time);
		} else if (data.action == 'update') {
			$.each(data.watchers, function(n, info) {
				$('#watcher-' + info.name + ' .cpu').html(info.cpu);
				$('#watcher-' + info.name + ' .vsz').html(info.vsz);
				$('#watcher-' + info.name + ' .res').html(info.res);
			});
		}
	} catch (err) {
		console.log('Unknown message', evt.data, err);
	}
}

ws.onerror = function(evt) {
	console.log('[WebSocket][E]', evt.data);
}

ws_all.onmessage = function(evt) {
	try {
		var data = JSON.parse(evt.data);
		if (data.action == 'tail_append') {
			var dom = document.getElementById('tail_all');
			var lines = data.data.split("\n");
			for (var i = 0; i < lines.length; ++i) {
				if (lines[i].length > 0) dom.innerHTML = dom.innerHTML + '[' + data.watcher + ']' + lines[i] + "\n";
			}

			var len = dom.innerHTML.length;
			if (len > 8192) dom.innerHTML = dom.innerHTML.substring(len - 8192);
			
			$('#tail_all').scrollTop(99999999);
		}
	} catch (err) {
		console.log('Unknown message', evt.data, err);
	}
}

ws_all.onerror = function(evt) {
	console.log('[WebSocket][E]', evt.data);
}



